package com.ycsj.goldmedalnewconcept.fragment;

import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIM.GroupInfoProvider;
import io.rong.imkit.RongIM.LocationProvider;
import io.rong.imkit.RongIM.UserInfoProvider;
import io.rong.imkit.model.UIConversation;
import io.rong.imkit.widget.provider.CameraInputProvider;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imkit.widget.provider.LocationInputProvider;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.App;
import com.ycsj.goldmedalnewconcept.DemoContext;
import com.ycsj.goldmedalnewconcept.MainActivity;
import com.ycsj.goldmedalnewconcept.activity.MineConversationInfo;
import com.ycsj.goldmedalnewconcept.activity.SOSOLocationActivity;
import com.ycsj.goldmedalnewconcept.activity.UserInfoActivity;
import com.ycsj.goldmedalnewconcept.bean.AddressListresp;
import com.ycsj.goldmedalnewconcept.bean.friendInfo;
import com.ycsj.goldmedalnewconcept.bean.AddressListresp.friendListDetail;
import com.ycsj.goldmedalnewconcept.bean.AddressListresp.groupListDetail;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.picture.PhotoInputProvider;
import com.ycsj.goldmedalnewconcept.sortlistview.CharacterParser;
import com.ycsj.goldmedalnewconcept.sortlistview.ClearEditText;
import com.ycsj.goldmedalnewconcept.sortlistview.PinyinComparator;
import com.ycsj.goldmedalnewconcept.sortlistview.SideBar;
import com.ycsj.goldmedalnewconcept.sortlistview.SortAdapter;
import com.ycsj.goldmedalnewconcept.sortlistview.SortModel;
import com.ycsj.goldmedalnewconcept.sortlistview.SideBar.OnTouchingLetterChangedListener;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;
import com.ycsj.goldmedalnewconcept.R;

//通讯录
public class AddressListFragment extends Fragment implements OnRefreshListener {

	private Activity ctx;
	private View layout;
	private MainActivity parentActivity;
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortAdapter adapter;
	private ClearEditText mClearEditText;
	private PullToRefreshLayout prf;
	private PinyinComparator pinyinComparator;
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;
	public ArrayList<friendInfo> friendlist = new ArrayList<friendInfo>();
	public ArrayList<UserInfo> UserList = new ArrayList<UserInfo>();
	public ArrayList<Group> GroupList = new ArrayList<Group>();
	private int i = 0;
	private String account;
	private String disableGroup;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (layout == null) {
			ctx = this.getActivity();
			parentActivity = (MainActivity) getActivity();
			layout = ctx.getLayoutInflater().inflate(
					R.layout.fragment_addresslist, null);
		} else {
			ViewGroup parent = (ViewGroup) layout.getParent();
			if (parent != null) {
				parent.removeView(layout);
			}
		}
//		initViews(layout);
		
		account = SPUtil.getString(getActivity(), "account", "");
		disableGroup = SPUtil.getString(getActivity(), "disableGroup", "");
		return layout;
	}

	@Override
	public void onResume() {
		 i++;
//		 initDate(1);
//		 setOnListener();
		 GroupList = new ArrayList<Group>();
		 initViews(layout);
		super.onResume();
	}

	private void initViews(View view) {

		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) view.findViewById(R.id.sidrbar);
		dialog = (TextView) view.findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		prf = (PullToRefreshLayout) view.findViewById(R.id.refresh_view);

		sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
		mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);

		initDate(1);
		 setOnListener();
	}

	private void setOnListener() {

		prf.setOnRefreshListener(this);

		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}
			}
		});
		
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.e("test", "GroupList"+GroupList.size());
				
				if (position == 0) {
					
					Log.e("test1", "position"+position);
					Intent intent = new Intent(getActivity(),
							UserInfoActivity.class);
					intent.putExtra("c", SourceDateList.get(0).getSortID());
					intent.putExtra("role",
							SPUtil.getString(getActivity(), "role", ""));
					startActivity(intent);

				} else if (position >= 1 && position <= GroupList.size()) {
					Log.e("test2", "position"+position);
					if (RongIM.getInstance() != null)
						RongIM.getInstance().startGroupChat(getActivity(),
								SourceDateList.get(position).getSortID(),
								SourceDateList.get(position).getName());
					RongIM.getInstance().setCurrentUserInfo(
							UserList.get(position));
					SPUtils.put(getActivity(), "clickGroupid", SourceDateList
							.get(position).getSortID());
					SPUtils.put(getActivity(), "clickGroupname", SourceDateList
							.get(position).getName());
					SPUtils.put(getActivity(), "clickGroupicon",
							iconlist.get(position));
				} else {
					Log.e("test3", "position"+position);
					Log.e("test", "RongIM.getInstance()"+RongIM.getInstance());
					if (RongIM.getInstance() != null)
						Log.e("test", "run"+position);
						SPUtil.putString(ctx, "clickUserid",
								SourceDateList.get(position).getSortID());
						SPUtil.putString(ctx, "clickRole",
								SourceDateList.get(position).getSortStaus());
						Log.e("clickUserid", "clickUserid"+SourceDateList.get(position).getSortID());
						Log.e("role", "role"+SourceDateList.get(position).getSortStaus());

						RongIM.getInstance().startPrivateChat(
								getActivity(),
								SourceDateList.get(position).getSortID()
										+ SourceDateList.get(position)
												.getSortStaus(),
								SourceDateList.get(position).getName());
					
				}
			}
		});

		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s != null) {
					filterData(s.toString());
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	}

	private int flag;

	private void initDate(int method) {
		flag = method;
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		final Request request = new Request.Builder().url(
				Constant.ycsj_count_MessageCenter + "?type=13&c="
						+ SPUtil.getString(ctx, "account", "") + "&role="
						+ SPUtil.getString(ctx, "role", "") + "&platform=2")
				.build();
		//http://m.moregolden.com/ycsj_count/MessageCenter?type=13&c=13006314760&role=2&platform=2
		Call call = mOkHttpClient.newCall(request);
		call.enqueue(callBack);

	}

	private List<SortModel> filledData(ArrayList<friendInfo> friendlist) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		try {

			if (friendlist != null) {

				for (int i = 0; i < friendlist.size(); i++) {
					SortModel sortModel = new SortModel();
					sortModel.setName(friendlist.get(i).friend_name);
					sortModel.setSortID(friendlist.get(i).friend);
					sortModel.setSortStaus(friendlist.get(i).friend_type);
					sortModel.setSortIcon(friendlist.get(i).friend_headimg);
					// ����ת����ƴ��
					String pinyin = characterParser.getSelling(friendlist
							.get(i).friend_name);
					String sortString = pinyin.substring(0, 1).toUpperCase();

					// ������ʽ���ж�����ĸ�Ƿ���Ӣ����ĸ
					if (sortString.matches("[A-Z]")) {
						sortModel.setSortLetters(sortString.toUpperCase());
					} else {
						sortModel.setSortLetters("#");
					}

					mSortList.add(sortModel);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return mSortList;

	}

	private List<SortModel> filledData(String[] date) {
		List<SortModel> mSortList = new ArrayList<SortModel>();

		for (int i = 0; i < date.length; i++) {
			SortModel sortModel = new SortModel();
			sortModel.setName(date[i]);
			// ����ת����ƴ��
			String pinyin = characterParser.getSelling(date[i]);
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// ������ʽ���ж�����ĸ�Ƿ���Ӣ����ĸ
			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}

			mSortList.add(sortModel);
		}
		return mSortList;

	}

	/**
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<SortModel> filterDateList = new ArrayList<SortModel>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
		} else {
			if (filterDateList != null) {

				filterDateList.clear();
				for (SortModel sortModel : SourceDateList) {
					String name = sortModel.getName();
					if (name.indexOf(filterStr.toString()) != -1
							|| characterParser.getSelling(name).startsWith(
									filterStr.toString())) {
						filterDateList.add(sortModel);
					}
				}
			}
		}

		Collections.sort(filterDateList, pinyinComparator);

		adapter.updateListView(filterDateList);
	}

	Handler handler = new Handler();

	private ArrayList<String> iconlist;

	Callback callBack = new Callback() {

		@Override
		public void onResponse(Response arg0) throws IOException {

			try {

				String json = arg0.body().string();
				Gson gson = new Gson();
				
				Log.e("address", json);
				if ((!("{\"state\":\"-1\"}").equals(json))
						&& !json.contains("<html><head><title>")) {
					final AddressListresp fromJson = gson.fromJson(json,
							AddressListresp.class);
					ArrayList<String> Namelist = new ArrayList<String>();
					iconlist = new ArrayList<String>();
					if (fromJson == null || fromJson.friendList == null) {

					} else {

						for (int i = 0; i < fromJson.friendList.size(); i++) {
							Namelist.add(fromJson.friendList.get(i).NAME);
							iconlist.add(fromJson.friendList.get(i).HEADIMG);
						}
					}
					
					final String[] array = new String[Namelist.size()];
					for (int j = 0; j < Namelist.size(); j++) {
						array[j] = Namelist.get(j);
					}

					friendlist.removeAll(friendlist);

					if (fromJson.groupList.size() > 0) {
						for (groupListDetail groupInfo : fromJson.groupList) {

							GroupList.add(new Group(groupInfo.groupId,
									groupInfo.groupName, Uri
											.parse(groupInfo.groupIcon)));

						}
					}
					
					
					
					if (fromJson.friendList.size() > 0) {
						for (friendListDetail friendInfo : fromJson.friendList) {

//							friendlist.add(new friendInfo(friendInfo.USER_ID.substring(0,3)+"*****"+friendInfo.USER_ID.substring(8,friendInfo.USER_ID.length()),
									friendlist.add(new friendInfo(friendInfo.USER_ID,
									
									friendInfo.HEADIMG, friendInfo.NAME,
									friendInfo.ROLE));
							
						}
					}
					
					if (fromJson != null && fromJson.friendList != null) {
						String friendlistjson = gson
								.toJson(fromJson.friendList);
						if (friendlistjson != null) {
							try {
								SPUtil.putString(getActivity(),
										"friendlistjson", friendlistjson);
							} catch (Exception e) {
								
							}
						}
					}

					UserList.add(
							0,
							new UserInfo(SPUtil.getString(ctx, "account", "")
									+ SPUtil.getString(ctx, "role", ""), SPUtil
									.getString(ctx, "name", ""), Uri
									.parse(SPUtil.getString(ctx, "icon", ""))));

					for (friendInfo friendInfo : friendlist) {
						UserList.add(new UserInfo(friendInfo.friend
								+ friendInfo.friend_type,
								friendInfo.friend_name, Uri
										.parse(friendInfo.friend_headimg)));
					}

					try {
						for (UserInfo userInfoRefresh : UserList) {

							RongIM.getInstance().refreshUserInfoCache(
									userInfoRefresh);
						}
					} catch (Exception e) {
						
					}

					RongIM.setGroupInfoProvider(new GroupInfoProvider() {

						@Override
						public Group getGroupInfo(String arg0) {
							for (int i = 0; i < GroupList.size(); i++) {
								if (GroupList.get(i).getId().equals(arg0)) {
									return GroupList.get(i);
								}
							}
							return null;
						}
					}, true);

					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							SourceDateList = filledData(friendlist);
							SourceDateList.add(new SortModel(SPUtil.getString(
									ctx, "name", ""), "我", SPUtil.getString(
									ctx, "account", ""), "我", SPUtil.getString(
									ctx, "icon", "")));
							iconlist.add(SPUtil.getString(ctx, "icon", ""));
							for (int k = 0; k < fromJson.groupList.size(); k++) {
								SourceDateList.add(new SortModel(
										fromJson.groupList.get(k).groupName,
										"群", fromJson.groupList.get(k).groupId,
										"群",
										fromJson.groupList.get(k).groupIcon));
								iconlist.add(fromJson.groupList.get(k).groupIcon);
							}
							Collections.sort(SourceDateList, pinyinComparator);

							// 关闭下拉刷新
							if (null != prf && flag == 2) {
								prf.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
							}

							// if (i != 1) {
							if (i != 1&&iconlist!=null&&SourceDateList!=null) {
								adapter.updateListView(SourceDateList, iconlist,disableGroup,account);
							} else {
								
								try {
									adapter = new SortAdapter(getActivity(),
											SourceDateList, iconlist,disableGroup,account);
									sortListView.setAdapter(adapter);
								} catch (Exception e) {
									// TODO: handle exception
								}
							}

							// sortListView.setAdapter(adapter);
							RongIM.setUserInfoProvider(new UserInfoProvider() {

								@Override
								public UserInfo getUserInfo(String userId) {
									for (int i = 0; i < UserList.size(); i++) {
										if (UserList.get(i).getUserId()
												.equals(userId)) {
											Log.e("LoginActivity", UserList
													.get(i).getName()
													+ "---="
													+ i);
											return UserList.get(i);
											
										}
									}
									return null;
								}
							}, true);
						}
					}, 100);
				}
			} catch (Exception e) {

			}
		}

		@Override
		public void onFailure(Request arg0, IOException arg1) {

		}
	};

	@Override
	public void onRefresh() {
		 GroupList = new ArrayList<Group>();
		initDate(2);
	}
};












